<?php
/**
 * Created by PhpStorm.
 * User: hedonglin
 * Date: 2017/10/26
 * Time: 8:46
 */

namespace app\admin\controller;


use think\Controller;
use think\Request;
use think\Db;
use app\admin\model\Emp as EmpModel;
use app\admin\model\User as UserModel;

class Emp extends Controller
{
    public $table_emp = 'oes_emp';
    public $table_dept = 'oes_dept';
    public $table_user = 'user';

    /**
     * 员工页面视图
     * @return mixed
     */
    public function index(){
        $this->assign( "user",UserModel::all());
        return $this->fetch();
    }

    /**
     * 分页查询员工
     * @param int $pageNumber
     * @param int $pageSize
     * @param string $searchText
     * @return \think\response\Json
     */
    public function getList($pageNumber = 1, $pageSize = 5, $searchText = '') {
        $result = DB::table(array($this->table_emp=>'emp',$this->table_dept=>'dept',$this->table_user=>'user'))
            ->field('emp.*,dept.name as dname,user.username,user.nickname')
            ->where("emp.sysuser_id=user.id and emp.dept_id=dept.id")//连表条件
            ->where('emp.id = :id or emp.name LIKE :name or emp.work_number LIKE :work_number or dept.name LIKE :dname'
                ,['id'=>$searchText ,'name'=>'%'.$searchText.'%','work_number'=>'%'.$searchText.'%','dname'=>'%'.$searchText.'%'])//查询条件
            ->order("emp.id")->paginate($pageSize, false, ["page"=>$pageNumber]);
        return json($result);
    }

    /**
     * 新增
     * @param Request $request
     * @return \think\response\Json
     */
    public function addEmp(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['name', 'work_number', 'tel', 'duty', 'dept_id','note','sex','status',"sysuser_id"]);

        $result = EmpModel::create($data);
        // 返回数据
       if ($result) {
            return json(['success'=>true, "msg"=>'添加成功']);
        } else {
            return json(['success'=>false, "msg"=>'添加失败']);
        }
    }

    /**
     * 修改
     * @param Request $request
     * @return \think\response\Json
     */
    public function updateEmp(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['id','name', 'work_number', 'tel', 'duty', 'dept_id','note','sex','status',"sysuser_id"]);

        $result = EmpModel::update($data);
        // 返回数据
        if ($result) {
            return json(['success'=>true, "msg"=>'修改成功']);
        } else {
            return json(['success'=>false, "msg"=>'修改失败']);
        }
    }

    /**
     * 逻辑删除
     * @param Request $request
     * @return \think\response\Json
     */
    public function deleteEmp(Request $request) {
        // 获取参数仅包含数组中字段
        $data = $request->only(['id','status']);

        $result = EmpModel::update($data);
        // 返回数据
        if ($result) {
            return json(['success'=>true, "msg"=>'删除成功']);
        } else {
            return json(['success'=>false, "msg"=>'删除失败']);
        }
    }


}